import {
  Button,
  Image,
  Input,
  message,
  Modal,
  Space,
  Textarea
} from 'ant-design-vue'
import { defineComponent, ref } from 'vue'

import { userApi } from '@/apis'
import type { UserManageListItem } from '@/apis/userTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'

import BmUserDialog from './components/bmUserDialog'
import DetailDialog from './components/detailDialog'
import { useFreeze, useGiveScore } from './hooks'

export default defineComponent({
  name: 'UserManage',
  setup() {
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref<ProTableProps>({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await userApi.getUserManageList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        },
        formConfig: {
          items: [
            {
              field: 'keyword',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入微信昵称或者手机号',
                  style: {
                    width: '200px'
                  }
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '客户信息',
            minWidth: 200,
            field: 'avatar',
            slots: {
              default: 'avatar'
            }
          },
          {
            title: '成为客户时间',
            field: 'createTime',
            formatter: TABLE_FORMAT.Date,
            width: 150
          },
          {
            title: '最新消费时间',
            field: 'lastConsumeTime',
            formatter: TABLE_FORMAT.Date,
            width: 150
          },
          {
            title: '消费金额',
            field: 'lastConsumeAmount',
            formatter: [TABLE_FORMAT.SaveDecimal]
          },
          {
            title: '消费次数',
            field: 'consumeCounts'
          },
          {
            title: '当前积分',
            field: 'point'
          },
          {
            title: '累计积分',
            field: 'totalPoint'
          },
          {
            title: '邀请人',
            field: 'inviteName'
          },
          {
            title: '邀请时间',
            field: 'inviteTime',
            formatter: TABLE_FORMAT.Date,
            width: 150
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 250
          }
        ],
        pagerConfig: {
          pageSize: 10
        }
      }
    })
    async function refresh(callback: PromiseFunc) {
      try {
        tableRef.value.showLoading()
        await callback()
        await tableRef.value.table.commitProxy('query')
      } finally {
        tableRef.value.hideLoading()
      }
    }
    const { handleFreeze, handleActive } = useFreeze({ refresh })
    const { showChange, giveScoreNum, reason, handleGiveScore, showModal } =
      useGiveScore({ refresh })
    const detailDialog = ref<ComponentRef>({})
    function showScoreDetail(id: number) {
      detailDialog.value!.openDialog(id)
    }
    const bmUserDialog = ref<ComponentRef>({})
    function showBmUserDialog(id: number) {
      bmUserDialog.value!.openDialog(id)
    }

    const { showConfirm } = useDialog()
    //注销账户
    function handleLogOff(row: any) {
      showConfirm({
        content: `确认注销 ${row.mobile}（${row.nickname}）  这个账号？`,
        onOk() {
          refresh(async () => {
            await userApi.getLogOffUser(row.id)
            message.success('注销成功')
          })
        }
      })
    }

    return {
      tableRef,
      tableConfig,
      giveScoreNum,
      reason,
      showChange,
      detailDialog,
      bmUserDialog,
      handleFreeze,
      handleActive,
      handleLogOff,
      handleGiveScore,
      showModal,
      showScoreDetail,
      showBmUserDialog
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            avatar: ({ row }: { row: UserManageListItem }) => {
              return (
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}
                >
                  <Image
                    src={row.avatar}
                    style={{ width: '60px', height: '60px' }}
                  />
                  <div style={{ marginLeft: '10px' }}>
                    <span>{row.nickname}</span>
                    <br />
                    <span>{row.mobile}</span>
                  </div>
                </div>
              )
            },
            operation: ({ row }: { row: UserManageListItem }) => {
              return (
                <>
                  <Space>
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        this.showModal(row.id)
                      }}
                    >
                      赠送积分
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        this.showScoreDetail(row.id)
                      }}
                    >
                      积分明细
                    </Button>
                    {row.status === 0 ? (
                      <Button
                        type="link"
                        size="small"
                        onClick={() => {
                          this.handleFreeze(row.id)
                        }}
                      >
                        冻结账号
                      </Button>
                    ) : (
                      <Button
                        type="link"
                        size="small"
                        onClick={() => {
                          this.handleActive(row.id)
                        }}
                      >
                        启用账号
                      </Button>
                    )}
                  </Space>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      this.showBmUserDialog(row.id)
                    }}
                  >
                    关联的BM账户
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      this.handleLogOff(row)
                    }}
                  >
                    注销账号
                  </Button>
                </>
              )
            }
          }}
          {...this.tableConfig}
        />
        {/* 赠送积分 */}
        <Modal
          maskClosable={false}
          v-model:visible={this.showChange}
          title="赠送积分"
          width={400}
          onOk={() => {
            this.handleGiveScore()
          }}
        >
          <Input placeholder="请输入积分" v-model:value={this.giveScoreNum} />
          <br />
          <br />
          <Textarea
            placeholder="备注：赠送理由，不超过10字"
            maxlength={10}
            v-model:value={this.reason}
          />
        </Modal>
        {/* 积分明细 */}
        <DetailDialog ref="detailDialog" />
        <BmUserDialog ref="bmUserDialog" />
      </div>
    )
  }
})
